--[[
Birthday exporter for Group Calendar

All birthdays in GC are exported in the industry standard iCalendar format,
so they can be imported into Google Calendar, Apple's iCal, Facebook, 
MS Exchange, etc, etc

example:
lua mk_group_cal_ical.lua YOURACCOUNTNAME > calendar.ics

8)
]]


GUILD = "Savvy" -- change to your guild's name
SERVER = "Echo Isles" -- change to your server
TIMEZONE = "US/Pacific" -- change to your server's timezone
WOWPATH = "/Applications/World of Warcraft/" -- path to WoW's main directory


if arg[1] then
    ACCOUNT = string.upper(arg[1])
else
    print("usage: " .. arg[0] .. " ACCOUNTNAME > calendar.ics")
    os.exit()
end


function convertDateToMDY(date)
    daysInYear = function(y) return y % 4 == 0 and 366 or 365 end
    date = 1 + date -- ewww stinky off by one error.  January 0, 2000 does not exist!
    days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    year = 2000
    month = 1
    while date > daysInYear(year) do
        date = date - daysInYear(year)
        year = year + 1
    end
    if year % 4 == 0 then days[2] = days[2] + 1 end
    while date > days[month] do
        date = date - days[month]
        month = month + 1
    end
    return month, date, year
end
        

function printEvent(n, e)
    m, d, y = convertDateToMDY(e["mDate"])
    if e["mType"] == "Birth" then
        print("BEGIN:VEVENT")
        print("DTSTART;TZID=" .. TIMEZONE .. ":" 
                .. string.format("%04d%02d%02d", y, m, d))
        if e["mTitle"] then print("SUMMARY:" .. e["mTitle"]) end
        if e["mDescription"] then print("DESCRIPTION:" .. e["mDescription"]) end
        print("RRULE:FREQ=YEARLY")
        print("END:VEVENT")
    end
end


dofile(WOWPATH .."/WTF/Account/" .. ACCOUNT .. "/SavedVariables/GroupCalendar.lua")

print("BEGIN:VCALENDAR")
print("VERSION:2.0")
for k, v in pairs(gGroupCalendar_Database["Databases"]) do
    if string.find(string.upper(k), string.upper(SERVER)) == 1 
            and v["Guild"] 
            and string.upper(v["Guild"]) == string.upper(GUILD) then
        for _, n in pairs(v["Events"]) do
            for _, e in pairs(n) do
                printEvent(v["UserName"], e)
            end
        end
    end
end
print("END:VCALENDAR")